﻿using FCT551.Helper;
using FCT551.Models;
using FCT551.ViewModels;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace FCT551.Procedure
{
    public class SocketClient
    {
        public static updateHandler updatemessage;
        private readonly TcpClient _client;
        private NetworkStream _stream;
        private string _ip;
        private int _port;
        private int TimeOut = 5000;
        private string Message = "";
        private bool ResStatus = false;

        public SocketClient(string serverIp, int port)
        {
            _client = new TcpClient();
            _ip = serverIp;
            _port = port;
        }

        public async Task ConnectAsync()
        {
            try
            {
                await _client.ConnectAsync(_ip, _port);
                _stream = _client.GetStream();
                UpdateMessage("已连接到服务器！");
                Global.ClientISConnect = true;
                // 启动接收和发送任务
                await Task.Run(ReceiveMessagesAsync);
            }
            catch (Exception ex)
            {
                Global.ClientISConnect = false;
                UpdateMessage($"连接异常: {ex.Message}", LogLevel.Error);
            }
        }

        private async Task ReceiveMessagesAsync()
        {
            var buffer = new byte[1024];

            while (_client.Connected)
            {
                try
                {
                    int bytesRead = await _stream.ReadAsync(buffer, 0, buffer.Length);
                    if (bytesRead == 0)
                    {
                        Global.ClientISConnect = false;
                        // 服务器断开
                        break;
                    }
                    Message = Encoding.UTF8.GetString(buffer, 0, bytesRead);

                    ResStatus = true;
                    //UpdateMessage($"收到消息: {Message}");
                }
                catch (Exception ex)
                {
                    Global.ClientISConnect = false;
                    UpdateMessage($"接收错误: {ex.Message}", LogLevel.Error);
                    break;
                }
            }
        }

        public async Task<string> ReceiveRes()
        {
            string result = "";
            Stopwatch stopwatch = Stopwatch.StartNew();
            while (true)
            {
                if (ResStatus)
                {
                    result = Message;
                    Message = "";
                    break;
                }
                if (stopwatch.ElapsedMilliseconds > TimeOut)
                {
                    break;
                }
                await Task.Delay(10);
            }
            ResStatus = false;
            return result;
        }

        public async Task SendMessagesAsync(string a)
        {
            if (_client.Connected)
            {
                try
                {
                    string input = a;
                    byte[] data = Encoding.UTF8.GetBytes(input);
                    await _stream.WriteAsync(data, 0, data.Length);
                }
                catch (Exception ex)
                {
                    Global.ClientISConnect = false;
                    UpdateMessage($"发送错误: {ex.Message}", LogLevel.Error);
                }
            }
        }

        public void close()
        {
            Global.ClientISConnect = false;
            _client?.Close();
        }

        private void UpdateMessage(string msg, LogLevel logLevel = LogLevel.Info)
        {
            Application.Current.Dispatcher.BeginInvoke(() =>
            {
                updatemessage?.Invoke(msg, logLevel);
            });
        }
    }
}